# -*- coding: UTF-8 -*-
from flask import g, url_for, session, current_app
from ..models import  db, User

INVITE_1 = '邀请你'

INVITE_2 = '邀请2'
INVITE_VISITER = '邀请3'


def get_share_url():
    uid = None
    share_text = INVITE_VISITER
    if g.user:
        if g.user.role == 'teacher':
            uid = g.user.id
            share_text = INVITE_1
        else:
            share_text = INVITE_2
    config = current_app.config
    share_url = config.get('SITE_DOMAIN') + url_for('site.share_redirect', uid=uid)
    return share_url, share_text


def save_invite_id(uid):
    session.permanent = True
    session['inviter_id'] = int(uid)


def delete_invite_id():
    if 'inviter_id' in session:
        session.pop('inviter_id', None)


def create_openid_invites(user):
    """
    在openid表中记录其邀请人
    """
    openid = OpenID()
    openid.user = user
    openid.invites = 0
    if 'inviter_id' in session:
        openid.inviter_id = session['inviter_id']
    db.session.add(openid)
    db.session.commit()
    delete_invite_id()


def add_inviter(uid):
    """
    user_id = uid,查数据库找出其邀请人，将其邀请人的邀请数+1
    测试方法：
    把邮箱注销掉
    然后点激活链接：
    http://localhost:5000/account/check_verify?user_id=517&token=qD4cLPah8l5AEDDkokIc
    """
    me = OpenID.query.filter(OpenID.user_id == uid).first()
    if not me:
        return
    openid = OpenID.query.filter(OpenID.user_id == me.inviter_id).first()
    if openid:
        if not openid.invites:
            openid.invites = 0
        openid.invites += 1
        db.session.commit()
    else:
        user = User.query.filter(User.id == me.inviter_id).first()
        if not user:
            return
        openid = OpenID()
        openid.user = user
        openid.invites = 1
        db.session.add(openid)
        db.session.commit()